package com.ruoyi.swla2.controller;

import java.io.File;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CoordinateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.swla2.domain.GisLine;
import com.ruoyi.swla2.mapper.GisPointMapper;
import com.ruoyi.swla2.model.PointTypeCountModel;
import com.ruoyi.swla2.service.IGisLineService;
import com.ruoyi.swla2.util.JtsUtils;
import com.ruoyi.swla2.util.OperatorTransform;
//import com.ruoyi.swla2.util.WKTTransform;
import org.aspectj.weaver.loadtime.Aj;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.io.ParseException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.swla2.domain.GisPoint;
import com.ruoyi.swla2.service.IGisPointService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * GIS管网-管点Controller
 *
 * @author gdqt
 * @date 2023-11-26
 */
@RestController
@RequestMapping("/swla2/gisPoint")
public class GisPointController extends BaseController {
    @Autowired
    private IGisPointService gisPointService;

    @Autowired
    private IGisLineService gisLineService;

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping("/test")
    public void test() {
        List<GisPoint> records = gisPointService.selectGisPointList(new GisPoint());
        String prefix = "JS";
        AtomicInteger id = new AtomicInteger(records.size() + 1);
        File file = FileUtil.file("C:\\Users\\1\\Desktop\\nx_wkt.txt");
        List<String> fileLines = FileUtil.readLines(file, "UTF-8");
//        List<String> geomLines = fileLines.stream().map(item -> item.substring(0, item.indexOf("))") + 2)).collect(Collectors.toList());
        List<GisPoint> pointList = new ArrayList<>();
        fileLines.forEach(item -> {
//            Geometry geometry = WKTTransform.coordinateTransform(item, 4547, 4326);
//            Coordinate[] coordinates = geometry.getCoordinates();
//            for (int i = 0; i < coordinates.length; i++) {
//                Coordinate coordinate = coordinates[i];
//                GisPoint point = new GisPoint();
//                point.setX(coordinate.getX());
//                point.setY(coordinate.getY());
//                point.setH(coordinate.getZ());
//                point.setGeom("POINT(" + coordinate.getX() + " " + coordinate.getY() + ")");
//                pointList.add(point);
//            }
        });

        System.out.println("原始点个数：" + pointList.size());
        List<GisPoint> distinctPointList = CollUtil.distinct(pointList, GisPoint::getGeom, true);
        System.out.println("去重点个数：" + distinctPointList.size());


        distinctPointList.forEach(item -> {
            item.setLayerId(5);
            item.setScode("1");
            int index = id.getAndIncrement();
            item.setExpNo(prefix + String.format("%06d", index));
            gisPointService.insertGisPoint(item);
        });
    }

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping("/testDygq")
    public void testDygq() {
        List<GisPoint> records = gisPointService.selectGisPointList(new GisPoint());
        String prefix = "JS";
        AtomicInteger id = new AtomicInteger(records.size() + 1);
        File file = FileUtil.file("C:\\Users\\1\\Desktop\\dygq_wkt.txt");
        List<String> fileLines = FileUtil.readLines(file, "UTF-8");

        List<GisPoint> pointList = new ArrayList<>();
        fileLines.forEach(line -> {
            try {
                LineString lineString = JtsUtils.createLineStringByWKT(line);
                Coordinate[] coordinates = lineString.getCoordinates();

                Coordinate start = coordinates[0];
                String startStr = "POINT(" + start.getX() + " " + start.getY() + ")";
                System.out.println(startStr);
                GisPoint pointStart = new GisPoint();
                pointStart.setX(start.getX());
                pointStart.setY(start.getY());
                pointStart.setH(0D);
                pointStart.setGeom(startStr);
                pointList.add(pointStart);


                Coordinate end = coordinates[coordinates.length - 1];
                String endStr = "POINT(" + end.getX() + " " + end.getY() + ")";
                System.out.println(endStr);

                GisPoint pointEnd = new GisPoint();
                pointEnd.setX(end.getX());
                pointEnd.setY(end.getY());
                pointEnd.setH(0D);
                pointEnd.setGeom(endStr);
                pointList.add(pointEnd);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        });

        System.out.println("原始点个数：" + pointList.size());
        List<GisPoint> distinctPointList = CollUtil.distinct(pointList, GisPoint::getGeom, true);
        System.out.println("去重点个数：" + distinctPointList.size());

        distinctPointList.forEach(item -> {
            item.setLayerId(27);
            item.setScode("1");
            int index = id.getAndIncrement();
            item.setExpNo(prefix + String.format("%06d", index));
            gisPointService.insertGisPoint(item);
        });
    }

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping("/generatePoint")
    public void generatePoint() {
//        String pointStr = "[[113.6933400409184,27.98855598513448],[113.6950990792144,28.00004618159975],[113.69914629416155,27.994249102012148],[113.70426476556283,27.99394304788428],[113.71093966213395,27.989277323812825],[113.7164656405751,27.997648673306173],[113.70688877476645,27.990358932303884],[113.7067843407619,27.987894462137575],[113.70325353103127,27.98741998732131],[113.70829302598904,28.002028281004513],[113.704292505218,28.00074617703915],[113.69845179782213,27.982596012840506],[113.70521825861306,27.993635292519834],[113.71086564548712,27.986880685045428],[113.71228492303264,27.989129304111152],[113.6972053387942,27.979194877271027],[113.70327278618078,28.002450218869143],[113.72081759754033,27.991747030135933],[113.70639186973852,27.998229824558965],[113.70284451015283,27.98633528683751],[113.71837337099412,27.99177974814534],[113.71757125536058,27.99264536507741],[113.6972225171669,27.981002721865245],[113.69837297882611,27.99316852583975],[113.71006800387907,27.98156197716067],[113.72022319312282,27.988433638094364],[113.71094560306985,27.98224972142313],[113.70809402513585,28.005350680095294],[113.70455188245235,27.999537623919387],[113.70982030465075,27.98912450518028],[113.7001743697249,27.98663719379107],[113.70637110044625,27.985238633506853],[113.7000973653505,27.988011191272705],[113.69653373449276,27.991241514367402],[113.7074905706599,27.984522583975288],[113.70667834157997,27.994866747536783],[113.70729058422134,27.98859373638825],[113.6994115716704,27.988047155897043],[113.71394360148146,27.981393380185047],[113.69634956379575,28.000818645293904],[113.69960186742236,27.99164249159538],[113.71393698991739,27.99045825278431],[113.71291216777958,27.979024063205404],[113.70193923869326,27.984434157886493],[113.69855840285629,27.989444131409957],[113.70271660976987,27.99266919468796],[113.70395122598877,27.998619200289088],[113.704811455362,27.9903084150282],[113.71007408958741,27.992791400313845],[113.69616355687916,27.993831512888047],[113.70990687246794,27.99511916364182],[113.72089345727288,27.99170476140098],[113.69987420968887,27.995946203636226],[113.70585757845157,27.9897058635248],[113.71297395368167,27.991982530886414],[113.71080240608103,27.982816334115544],[113.71540016089295,27.99161260552147],[113.70563358864261,27.99068865453504],[113.70787603090213,27.98915074108645],[113.70438592514539,27.990862777231563],[113.6925833717048,27.986705986766108],[113.7071033673123,27.99377465758039],[113.70240923645704,27.991271371301746],[113.69746646665827,27.989959357111395],[113.69929312242817,27.97937762682859],[113.70085108960879,27.99282511534002],[113.70139257563694,27.9900582070712],[113.70292551637579,27.9852394298374],[113.70631693573223,27.99160334288657],[113.70946383713424,28.00521683265379],[113.7078126029767,27.995109471084973],[113.70631647109461,27.9931665485029],[113.71241139254919,27.985504358982148],[113.69808759249884,27.987741351706834],[113.70892813612521,28.005425607100253],[113.71106689460238,27.99835946754612],[113.70267683571927,27.993065423825506],[113.71633318020886,27.98650721623952],[113.71632981504685,27.988765103639576],[113.7012809686172,27.989740775996435],[113.70205043611493,27.99159293069472],[113.70610930973824,27.99829981399977],[113.70773645294702,28.001120131880132],[113.70431968700836,27.99603396254691],[113.71039149448772,27.994105125931114],[113.70917203686953,28.000060968123694],[113.70531036247507,27.990907138620827],[113.70217724992185,27.982971370020365],[113.71076345490953,27.983674785927178],[113.71372394636668,27.99491119157832],[113.70828771121843,27.99658026997467],[113.7129671662028,27.995070038448404],[113.70543140250071,27.990942122606864],[113.70925409172898,27.99211867220082],[113.70381764878094,27.987657703803055],[113.70360647472839,27.99738450249613],[113.71637034922351,27.99306350420686],[113.70638185661416,27.991800859865634],[113.70103034172438,28.003388200355346],[113.711679853709,27.99257738896697]]";
        String pointStr = "[[113.700992,28.014276],[113.73299,27.971706],[113.777014,27.996326],[113.694046,28.017908]]";
        JSONArray jsonArray = JSONUtil.parseArray(pointStr);
        int index = 6001;
        for (Object json : jsonArray) {
            String[] points = json.toString().replace("[", "").replace("]", "").split(",");
            GisPoint gisPoint = new GisPoint();
            gisPoint.setX(Double.valueOf(points[0]));
            gisPoint.setY(Double.valueOf(points[1]));
            gisPoint.setLayerId(34);
            gisPoint.setScode("2");
            gisPoint.setExpNo("JS" + String.format("%06d", index));
            gisPoint.setGeom("POINT(" + points[0] + " " + points[1] + ")");
            index++;

            gisPointService.insertGisPoint(gisPoint);
        }
    }

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @PostMapping("/getPointFeatureData")
    public AjaxResult getPointFeatureData(@RequestBody Map<String, Object> queryMap) {
//        String key = queryMap.get("key").toString();
//        String value = queryMap.get("value").toString();
//        String operator = queryMap.get("operator").toString();
//        String transformOperator = OperatorTransform.transform(operator);
//        String query;
//        if (operator.equals("LIKE")) {
//            queryMap.put("value", "'%" + value + "%'");
//            query = key + transformOperator + "'%" + value + "%'";
//        } else {
//            query = key + transformOperator + "'" + value + "'";
//        }

//        queryMap.put("operator", transformOperator);

        List<GisPoint> gisPointList = gisPointService.getPointFeatureData(queryMap);

        return success(gisPointList);
    }

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @PostMapping("/getPointTypeCount")
    public AjaxResult getPointTypeCount(@RequestBody Map<String, Object> queryMap) {
        System.out.println(queryMap);
        List<GisPoint> gisPointList = gisPointService.getPointTypeCount(queryMap);
        Map<String, List<GisPoint>> groupedGisPointList = gisPointList.stream().collect(Collectors.groupingBy(GisPoint::getScode));

        List<PointTypeCountModel> modelList = new ArrayList<>();
        groupedGisPointList.forEach((pointType, dataList) -> {
            PointTypeCountModel model = new PointTypeCountModel();
            model.setPointType(pointType);
            model.setCount(dataList.size());
            modelList.add(model);
        });

        return success(modelList);
    }

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @PostMapping("/getPointAlarmData")
    public AjaxResult getPointAlarmData(@RequestBody Map<String, Object> queryMap) {
        System.out.println(queryMap);
        LocalDate now = LocalDate.now();
        LocalDate mDate = now.minusYears(Long.valueOf(queryMap.get("featureYears").toString()));
        queryMap.put("mDate", mDate);
        List<GisPoint> gisPointList = gisPointService.getPointAlarmData(queryMap);
        return success(gisPointList);
    }

    /**
     * 查询GIS管网-管点列表
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping("/list")
    public TableDataInfo list(GisPoint gisPoint) {
        List<GisPoint> list = gisPointService.selectGisPointList(gisPoint);
        return getDataTable(list);
    }

    /**
     * 导出GIS管网-管点列表
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @Log(title = "GIS管网-管点", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GisPoint gisPoint) {
        List<GisPoint> list = gisPointService.selectGisPointList(gisPoint);
        ExcelUtil<GisPoint> util = new ExcelUtil<GisPoint>(GisPoint.class);
        util.exportExcel(response, list, "GIS管网-管点数据");
    }

    /**
     * 获取GIS管网-管点详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(gisPointService.selectGisPointById(id));
    }

    /**
     * 新增GIS管网-管点
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @Log(title = "GIS管网-管点", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GisPoint gisPoint) {
        return toAjax(gisPointService.insertGisPoint(gisPoint));
    }

    /**
     * 修改GIS管网-管点
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @Log(title = "GIS管网-管点", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GisPoint gisPoint) {
        GisPoint record = gisPointService.selectGisPointById(gisPoint.getId());
        if (!NumberUtil.equals(record.getX(), gisPoint.getX()) || !NumberUtil.equals(record.getY(), gisPoint.getY())) {
            // 经纬度改变
            gisLineService.updateGisLinePointsXY(record.getExpNo(), record.getX() + " " + record.getY(), gisPoint.getX() + " " + gisPoint.getY());
        }
        if (!NumberUtil.equals(record.getDeep(), gisPoint.getDeep())) {
            // 埋深改变
            gisLineService.updateGisLinePointsDeep(record.getExpNo(), gisPoint.getDeep());
        }
        gisPoint.setGeom("POINT(" + gisPoint.getX() + " " + gisPoint.getY() + ")");
        return toAjax(gisPointService.updateGisPoint(gisPoint));
    }

    /**
     * 删除GIS管网-管点
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @Log(title = "GIS管网-管点", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(gisPointService.deleteGisPointByIds(ids));
    }

    public static void main(String[] args) {
        String pointStr = "[[113.6933400409184,27.98855598513448],[113.6950990792144,28.00004618159975],[113.69914629416155,27.994249102012148],[113.70426476556283,27.99394304788428],[113.71093966213395,27.989277323812825],[113.7164656405751,27.997648673306173],[113.70688877476645,27.990358932303884],[113.7067843407619,27.987894462137575],[113.70325353103127,27.98741998732131],[113.70829302598904,28.002028281004513],[113.704292505218,28.00074617703915],[113.69845179782213,27.982596012840506],[113.70521825861306,27.993635292519834],[113.71086564548712,27.986880685045428],[113.71228492303264,27.989129304111152],[113.6972053387942,27.979194877271027],[113.70327278618078,28.002450218869143],[113.72081759754033,27.991747030135933],[113.70639186973852,27.998229824558965],[113.70284451015283,27.98633528683751],[113.71837337099412,27.99177974814534],[113.71757125536058,27.99264536507741],[113.6972225171669,27.981002721865245],[113.69837297882611,27.99316852583975],[113.71006800387907,27.98156197716067],[113.72022319312282,27.988433638094364],[113.71094560306985,27.98224972142313],[113.70809402513585,28.005350680095294],[113.70455188245235,27.999537623919387],[113.70982030465075,27.98912450518028],[113.7001743697249,27.98663719379107],[113.70637110044625,27.985238633506853],[113.7000973653505,27.988011191272705],[113.69653373449276,27.991241514367402],[113.7074905706599,27.984522583975288],[113.70667834157997,27.994866747536783],[113.70729058422134,27.98859373638825],[113.6994115716704,27.988047155897043],[113.71394360148146,27.981393380185047],[113.69634956379575,28.000818645293904],[113.69960186742236,27.99164249159538],[113.71393698991739,27.99045825278431],[113.71291216777958,27.979024063205404],[113.70193923869326,27.984434157886493],[113.69855840285629,27.989444131409957],[113.70271660976987,27.99266919468796],[113.70395122598877,27.998619200289088],[113.704811455362,27.9903084150282],[113.71007408958741,27.992791400313845],[113.69616355687916,27.993831512888047],[113.70990687246794,27.99511916364182],[113.72089345727288,27.99170476140098],[113.69987420968887,27.995946203636226],[113.70585757845157,27.9897058635248],[113.71297395368167,27.991982530886414],[113.71080240608103,27.982816334115544],[113.71540016089295,27.99161260552147],[113.70563358864261,27.99068865453504],[113.70787603090213,27.98915074108645],[113.70438592514539,27.990862777231563],[113.6925833717048,27.986705986766108],[113.7071033673123,27.99377465758039],[113.70240923645704,27.991271371301746],[113.69746646665827,27.989959357111395],[113.69929312242817,27.97937762682859],[113.70085108960879,27.99282511534002],[113.70139257563694,27.9900582070712],[113.70292551637579,27.9852394298374],[113.70631693573223,27.99160334288657],[113.70946383713424,28.00521683265379],[113.7078126029767,27.995109471084973],[113.70631647109461,27.9931665485029],[113.71241139254919,27.985504358982148],[113.69808759249884,27.987741351706834],[113.70892813612521,28.005425607100253],[113.71106689460238,27.99835946754612],[113.70267683571927,27.993065423825506],[113.71633318020886,27.98650721623952],[113.71632981504685,27.988765103639576],[113.7012809686172,27.989740775996435],[113.70205043611493,27.99159293069472],[113.70610930973824,27.99829981399977],[113.70773645294702,28.001120131880132],[113.70431968700836,27.99603396254691],[113.71039149448772,27.994105125931114],[113.70917203686953,28.000060968123694],[113.70531036247507,27.990907138620827],[113.70217724992185,27.982971370020365],[113.71076345490953,27.983674785927178],[113.71372394636668,27.99491119157832],[113.70828771121843,27.99658026997467],[113.7129671662028,27.995070038448404],[113.70543140250071,27.990942122606864],[113.70925409172898,27.99211867220082],[113.70381764878094,27.987657703803055],[113.70360647472839,27.99738450249613],[113.71637034922351,27.99306350420686],[113.70638185661416,27.991800859865634],[113.70103034172438,28.003388200355346],[113.711679853709,27.99257738896697]]";
        JSONArray jsonArray = JSONUtil.parseArray(pointStr);
        int index = 6001;
        for (Object json : jsonArray) {
            String[] points = json.toString().replace("[", "").replace("]", "").split(",");
            GisPoint gisPoint = new GisPoint();
            gisPoint.setX(Double.valueOf(points[0]));
            gisPoint.setY(Double.valueOf(points[1]));
            gisPoint.setLayerId(34);
            gisPoint.setScode("7");
            gisPoint.setExpNo("JS" + String.format("%06d", index));
            gisPoint.setGeom("POINT(" + points[0] + " " + points[1] + ")");
            index++;

            System.out.println(JSONUtil.toJsonStr(gisPoint));
        }
    }
}
